/*
 * @Author: zhaohui yuan
 * @Date: 2023-06-14 17:25:25
 * @Purpose: 通用混合器
 */

import {mapMutations, mapState} from "vuex";
import globalData from "@/globalData";

export default {
  data() {
    return {
      $query: {}, // 页面参数
      $globalData: {}, // 全局变量
    };
  },

  mounted() {
    this.$globalData = globalData;
  },

  onLoad(options) {
    this.$query = options;
    this.$globalData = globalData;

    // #ifdef MP-WEIXIN
    // 激活分享朋友圈按钮
    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    // #endif
  },

  /**
   * 分享到好友
   */
  onShareAppMessage() {
    return {
      title: "",
      path: "",
      imageUrl: "",
    };
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: "",
      path: "",
      imageUrl: "",
    };
  },

  methods: {

    /**
     * 返回上一步
     */
    goBack() {
		uni.navigateBack();
	},
	
	/**
	 * 判断值是否不为空
	 * @param {Object} val
	 */
	isNotNull(val){
		if(val!=='undefined' && val!=="" && val!=null){
			return true
		}
		return false
	},
	
	/**
	 * 提示框
	 * statu: success、error、loading、none
	 */
	showMSG(statu,msg){
		wx.showToast({
			icon: statu,
			title: msg,
			duration: 2000
		});
	},

  /**
	* 生成uuid
	*/
	guid() {
		let uuid = ''
		for (let i = 0; i < 8; i++) {
			if(i == 0){
				uuid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
			}else{
				uuid += (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
			}
		}
		return uuid
	},

  //转义HTML代码
  escape2Html (str) {
    let arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
    if(this.isNotNull(str)){
      return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) { return arrEntities[t]; });
    }
  },

  //转义HTML代码
	escape2Html2 (str){
		return str.replace(/(\r\n|\n|\r)/gm, '<br />');
	},

  /**
	 * 获取当前时间并格式化为yyyy-MM-dd HH:mm:ss函数
	 * @return 得到类似 2021-06-23 12:07:33 的值
	 */
	_getTimes() {
    const thisDay= new Date();
    const year = thisDay.getFullYear();       //年
    const month = thisDay.getMonth() + 1;     //月
    const day = thisDay.getDate();            //日
    const hh = thisDay.getHours();            //时
    const mm = thisDay.getMinutes();          //分
    const ss = thisDay.getSeconds();          //秒
    let timer = year + "-";
    if(month < 10)  
    timer += "0";
    timer += month + "-";
    if(day < 10)
    timer += "0";
    timer += day + " ";
    if(hh < 10)
    timer += "0";
      timer += hh + ":";
    if (mm < 10) 
    timer += '0'; 
    timer += mm + ":"; 
    if (ss < 10) 
    timer += '0'; 
    timer += ss; 
    return (timer);
  },

  /**
	 * 计算日期差：不足一天按一天算，即向上取值
	 * startTime 今天
	 * endTime   上架时间
	 * 返回天数差
	 */
	comparisonDate(startTime, endTime) {
		// 日期格式化
		let start_date = new Date(startTime.replace(/-/g, "/"));
		let end_date = new Date(endTime.replace(/-/g, "/"));
		// 转成毫秒数，两个日期相减
		let ms = start_date.getTime() - end_date.getTime();
		// 转换成天数(向上取整，不足一天按一天算)
		let day = Math.ceil(ms / (1000 * 60 * 60 * 24));
		return day;
	},
	
	/**
	 * 倒计时
	 */
	countdowm(timestamp, defaulttext) {
		let self = this
		let now = new Date()//获取当前时间戳
		let future = new Date(timestamp.replace(/-/g,"/"))//距离的时间
		let index = (future-now)/1000/(60*60*24)
		let day = parseInt(index)//天
		if(day > 3 || day == 3){
			self.endTimeContent = day + '天后结束';
		}else{
			let timer = setInterval(function() {
				let nowTime = new Date();
				let endTime = new Date(timestamp.replace(/-/g,"/")); //timestamp * 1000
				let t = endTime.getTime() - nowTime.getTime();
				if (t > 0) {
					let day = Math.floor(t / 86400000);
					let hour = Math.floor((t / 3600000) % 24);
					let min = Math.floor((t / 60000) % 60);
					let sec = Math.floor((t / 1000) % 60);
					if (day > 0) {
						hour = day * 24 + hour;
					}
					hour = hour < 10 ? "0" + hour : hour;
					min = min < 10 ? "0" + min : min;
					sec = sec < 10 ? "0" + sec : sec;
					self.endTimeContent = `${hour}:${min}:${sec}`;
				} else {
					clearInterval(timer);
					self.endTimeContent = defaulttext;
				}
			}, 1000);
		}
	},

  /**
	 * dateStr为相加前的时间， days 为 需要相加的天数
	 * @param {Object} date
	 * @param {Object} days
	 */
	addDateTime(dateStr, days) {
		let date = new Date(dateStr.replace(/-/g,"/"));
		date.setDate(date.getDate() + days);
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
		let hours = date.getHours();
		let minutes = date.getMinutes();
		let seconds = date.getSeconds();
		month = month < 10 ? "0" + month : month;
		day = day < 10 ? "0" + day : day;
		hours = hours < 10 ? "0" + hours : hours;
		minutes = minutes < 10 ? "0" + minutes : minutes;
		seconds = seconds < 10 ? "0" + seconds : seconds;
		let time = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
		return time;
	},

  /**
	 * 提示框
	 * statu: success、error、loading、none
	 */
	showMSG(statu,msg){
		wx.showToast({
			icon: statu,
			title: msg,
			duration: 2000
		});
	},

  // 跳转到meily小程序页面
  toMiniProgram(url) {
    uni.navigateToMiniProgram({
      appId: 'wx5221ade9a28dd5f3',
      path: url,
      extraData: {
        envVersion: 'trial' // 指定目标小程序的版本，可以是 'develop'、'trial' 或 'release'
      },
      success() {
        console.log('跳转成功');
      },
      fail(err) {
        console.error('跳转失败', err);
      }
    })
  },
	
    ...mapMutations(["SET_USER_INFO"]),
  },

  computed: {
    ...mapState(["userInfo"]),
  },
};
